
const md5 = require('js-md5');
const fs = require('fs');

class HTMLIndexMD5Plugin {

  scriptRegExp = /(?=<script.*?>)/;

  constructor(options) {
    this.options = options;
  }

  apply(compiler) {
    let self = this;
    console.log('HTMLMD5Plugin 启用')
    compiler.hooks.emit.tap('HTMLMD5Plugin', compilation => {
      // compilation - 此次打包上下文
      for (const name in compilation.assets) {
        if (name.endsWith('.html')) {
          let content = compilation.assets[name].source();
          let htmlMd5 = md5(content);

          let js = `<script>window.PAGE_MD5 = '${htmlMd5}'</script>`;
          let html = content.split(self.scriptRegExp);
          let firstScriptIndex = html.findIndex(code => code.startsWith('<script'));
          html.splice(firstScriptIndex, 0, js);
          content = html.join('');

          Object.assign(compilation.assets[name], {
            htmlMd5,
            source: () => content,
            size: content.length
          })

          Object.assign(compilation.assets[name], {
            buffer: undefined, // 写出文件的时候，node_modules\webpack\lib\Compiler.js[693] 会调用当前对象的 buffer 或 source方法，自定buffer为undefined，强制调用source方法
            source: () => content,
            size: content.length
          })
        }
      }
    })


    compiler.hooks.assetEmitted.tap('HTMLMD5Plugin', (file, info) => {
      if (info.source.htmlMd5){
        let outputPath = info.outputPath;
        fs.writeFile(outputPath + '/' + file +'.md5', info.source.htmlMd5, () => { });
      }
    });

  }
}

module.exports = HTMLIndexMD5Plugin;